<?php
/**
 * Note:     [Description]
 * Author:   longhui.huang <1592328848@qq.com>
 * DateTime: 2024/3/7 15:08
 */
declare(strict_types=1);

namespace App\Dao;

use App\Model\RoleModel;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;

class RoleDao extends BaseDao
{
    protected function setModel(): string
    {
        return RoleModel::class;
    }

    /**
     * 根据用户ID查询
     *
     * @param int $userId 用户ID
     *
     * @return array
     */
    public function findByUserId(int $userId)
    {
        $builder = new QueryBuilder();

        $fields   = [
            'role.*',
            'role.roleId as role_role_id, role.name as role_name, role.dataScope as role_data_scope',
            'role.level as role_level, role.description as role_description, role.createBy as role_create_by',
            'role.updateBy as role_updateBy, role.createTime as role_create_time, role.updateTime as role_update_time',
            'menu.menuId as menu_id, menu.title as menu_title, menu.permission as menu_permission',
            'dept.deptId as dept_id, dept.name as dept_name'
        ];
        $fieldStr = join(',', $fields);
        $builder->fields($fieldStr);
        $builder->join('sys_roles_menus srm', 'role.roleId = srm.roleId', 'LEFT')
                ->join('sys_menu menu', 'menu.menuId = srm.menuId', 'LEFT')
                ->join('sys_roles_depts srd', 'role.roleId = srd.roleId', 'LEFT')
                ->join('sys_dept dept', 'dept.deptId = srd.deptId', 'LEFT')
                ->join('sys_users_roles ur', 'role.roleId = ur.roleId', 'LEFT')
                ->where('role.roleId = ur.roleId')
                ->where('ur.userId', $userId)
                ->get('sys_role role');

        $res = DbManager::getInstance()->query($builder, true)->getResult();
        return $res ?: [];
    }
}
